<?php


namespace App\Http\Controllers\Admin;


use App\Models\Order;

class OrderController extends Controller
{
    /*
     * @api get /billing-api/a/orders 订单列表
     * @version 0.0.1
     * @group admin
     *
     * @param query int [pageSize] 页数，默认15
     * @param query int [page] 页码，默认1
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function index()
    {
        $this->validate($this->request, [
            "pageSize" => "integer|max:100|min:5",
            "page" => "integer|min:1"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $query = Order::query();
        $total = $query->count();
        $ordersObj = $query->orderBy('id', 'desc')->forPage($page, $pageSize)
            ->get();
        $items = [];
        if ($total) {
            /** @var Order $orderObj */
            foreach ($ordersObj as $orderObj) {
                $items[] = [
                    'id' => $orderObj->getId(),
                    'tradeNo' => $orderObj->getTradeNo(),
                    'totalAmount' => $orderObj->getTotalAmount(),
                    'product' => '一个月',
                    'status' => '',
                    'buyer_name' => 'xxx',
                    'createdAt' => $orderObj->getCreatedAt(),
                    'paidAt' => $orderObj->getPaidAt()
                ];
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items]);
    }

    /*
     * @api get /billing-api/a/orders/{orderId} 订单详情
     * @version 0.0.1
     * @group admin
     *
     * @param path int orderId 订单ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function show($orderId)
    {
        /** @var Order $orderObj */
        $orderObj = Order::find($orderId);
        $orderInfo = [
            'id' => $orderObj->getId(),
            'tradeNo' => $orderObj->getTradeNo()
        ];
        return $this->sendSuccessJson($orderInfo);
    }

    /*
     * @api post /billing-api/a/orders/{orderId}/refund 订单退款
     * @version 0.0.1
     * @group admin
     *
     * @param path int orderId 订单ID
     * @param body string remark 备注
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function refund($orderId)
    {
        $this->validate($this->request, [
            'remark' => 'string'
        ]);
        /** @var Order $orderObj */
        $orderObj = Order::find($orderId);
        $orderObj->setStatus(Order::ORDER_STATUS['refund']);
        $orderObj->save();
        // @todo 全部退款，部分退款



        return $this->sendSuccessJson();
    }
}